package com.yuyou.tas.lesson.service.comm;/**
 * Created by Administrator on 2018/6/6.
 */

import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson.JSONObject;
import com.yuyou.tas.lesson.service.ILessonResourceService;
import com.yuyou.tas.service.api.admin.service.CommJobAPI;
import com.yuyou.tas.service.api.lesson.entity.LessonResource;
import com.yuyou.tas.util.bean.FileMeta;
import com.yuyou.tas.util.bean.ResourceObj;
import com.yuyou.tas.util.enums.admin.CommJobEnums;
import com.yuyou.tas.util.exception.BusinessException;
import com.yuyou.tas.util.office.edit.DateUtils;
import com.yuyou.tas.util.office.edit.Token;
import com.yuyou.tas.util.tool.HttpClient;
import com.yuyou.tas.util.tool.LogUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Create by chengsiyuan on 2018/6/6-10:08
 **/
@Service
public class OfficeService {
        @Value("${office.service.url.prefix}")
        private String OFFICE_URL_PREFIX;

        final String COPY_SINGLE_URL =  "/office/copy/";//单个复制url
        final String COPY_MULTIPILE_URL =  "/office/copies";//多个复制url
        final String DELETE_SINGLE_URL =  "/office/delete/";//单个删除url
        final String DELETE_MULTIPILE_URL =  "/office/deletes/";//多个删除url
        final String APPID = "0001";//应用ID
        final Integer EXPIRE_HOUR = 1;//有效期-一个小时

        @Autowired
        private ILessonResourceService lessonResourceService;
            
        @Autowired
        private CommJobAPI commJobAPI;

        private final Logger logger = LoggerFactory.getLogger(this.getClass());

        /**
        * @author chengsiyuan
         * @throws Exception 
        * @create 2018/6/6-15:21
         * 单个复制
        **/
        public FileMeta copyFileMeta(int type,String resoureId,ResourceObj resourceObj) throws Exception{
        	if(StringUtils.isEmpty(resoureId)){
        		throw new BusinessException("resoureId为空");
        	}
            Map<String, String> map = new HashMap<>();
            map.put("token",Token.generate(APPID,resoureId, DateUtils.nowAddHour(EXPIRE_HOUR),Token.Permission.COPY));
            map.put("num" , "1");
            String str = HttpClient.get(OFFICE_URL_PREFIX + COPY_SINGLE_URL+resoureId , map);
            if(str == null || str.equals("") || JSONObject.parseArray(str,FileMeta.class) == null){
                throw new BusinessException("复制异常：源文件不存在-"+resoureId);
            }

            FileMeta newOne = JSONObject.parseArray(str,FileMeta.class).get(0);
            
            lessonResourceService.addResource(type,newOne.getResourceId(), resourceObj.getOrganizationId(), resourceObj.getClassId(), resourceObj.getUserId());
            
            return newOne;
        }
        
        public List<FileMeta> copyMultiFileMeta(String resoureId,int num) throws Exception{
        	if(StringUtils.isEmpty(resoureId)){
        		throw new BusinessException("resoureId为空");
        	}
        	if(num<=0){
        		throw new BusinessException("复制异常：数量等于0");
        	}
            Map<String, String> map = new HashMap<>();
            map.put("token",Token.generate(APPID,resoureId, DateUtils.nowAddHour(EXPIRE_HOUR),Token.Permission.COPY));
            map.put("num" , String.valueOf(num));
            String str = HttpClient.get(OFFICE_URL_PREFIX + COPY_SINGLE_URL+resoureId , map);
            if(str == null || str.equals("")){
                throw new BusinessException("复制异常：源文件不存在-"+resoureId);
            }
            List<FileMeta> newFiles = JSONObject.parseArray(str,FileMeta.class);
            if(newFiles.size()!=num){
            	throw new BusinessException("复制异常：数量不正确");
            }
            
            return newFiles;
        }

        /**
        * @author chengsiyuan
         * @throws Exception 
        * @create 2018/6/6-15:21
         * 多个复制
        **/
//        public Map<String , FileMeta> copyFileMetas(String[] resoureIds,ResourceObj resourceObj) throws Exception{
//        	if(resoureIds==null || resoureIds.length==0){
//        		throw new BusinessException("resoureIds为空");
//        	}
//            Map<String, String> map = new HashMap<>();
//            map.put("token",Token.generate(APPID,resoureIds[0], DateUtils.nowAddHour(EXPIRE_HOUR),Token.Permission.COPY));
//            map.put("resourceIds",String .join(",",resoureIds));
//            map.put("num" , "1");
//            String  str = HttpClient.post(COPY_MULTIPILE_URL , map,null);
//            Map<String , List<FileMeta>> resultMap = JSONObject.parseObject(str,new TypeReference<Map<String , List<FileMeta>>>(){});
//            
//            List<String> resources=new ArrayList<>();
//            Map<String , FileMeta> lastMap = new HashMap<>();
//            resultMap.forEach((k,v)->{
//                if(v == null || v.size() < 1){
//                    throw new BusinessException("复制异常："+k+"返回空filemeta");
//                }
//                FileMeta f = v.get(0);
//            	if(StringUtils.isEmpty(f.getResourceId())){
////            		throw new BusinessException("resoureId为空");
//            	}
//            	resources.add(f.getResourceId());
//            	lastMap.put(k , f);
//                });
//            lessonResourceService.addResources(1,resources, resourceObj.getOrganizationId(), resourceObj.getClassId(), resourceObj.getUserId());
//            return lastMap;
//        }

        @Transactional(rollbackFor=Exception.class,timeout=60)
        public void deleteFileMeta(String resourceId) throws Exception {
            LogUtil.info(logger , "开始删除office文件，资源ID： "+resourceId);
            if(resourceId==null){
                throw new BusinessException("resoureId不存在");
            }
            LessonResource lessonResource=lessonResourceService.selectByResourceId(resourceId);
            if(lessonResource==null){
                throw new BusinessException("lessonResource不存在");
            }
            Map<String, String> map = new HashMap<>();
            map.put("token",Token.generate(APPID,resourceId, DateUtils.nowAddHour(EXPIRE_HOUR),Token.Permission.DELETE));
            String  str = null;
            try {
                str = HttpClient.get(OFFICE_URL_PREFIX + DELETE_SINGLE_URL+resourceId , map);
                LogUtil.info(logger , "删除资源成功："+str);
            } catch (Exception e) {
                LogUtil.error(logger , "删除资源失败："+ExceptionUtil.getMessage(e));
                commJobAPI.updateJobStatus(lessonResource.getId(), CommJobEnums.type.resource.getValue(), CommJobEnums.tag.resource.getValue(), CommJobEnums.status.fail.getValue());
                return;
            }
            if(!str.equalsIgnoreCase("OK")){
            	commJobAPI.updateJobStatus(lessonResource.getId(), CommJobEnums.type.resource.getValue(), CommJobEnums.tag.resource.getValue(), CommJobEnums.status.fail.getValue());
                return;
            }
            commJobAPI.updateJobStatus(lessonResource.getId(), CommJobEnums.type.resource.getValue(), CommJobEnums.tag.resource.getValue(), CommJobEnums.status.success.getValue());
            lessonResourceService.delByResourceId(resourceId);
            

        }

//    public void deleteFileMetas(String[] resourceIds) throws Exception{
//        if(resourceIds==null || resourceIds.length==0){
//            throw new BusinessException("resoureIds为空");
//        }
//        Map<String, String> map = new HashMap<>();
//        map.put("token",Token.generate(APPID,resourceIds[0], DateUtils.nowAddHour(EXPIRE_HOUR),Token.Permission.DELETE));
//        map.put("resourceIds",String .join(",",resourceIds));
//        String  str = HttpClient.post(DELETE_MULTIPILE_URL , map);
//        if(!str.equalsIgnoreCase("OK")){
//            throw new BusinessException(str);
//        }
//        lessonResourceService.delByResourceIds(resourceIds);
//    }

    /*public static void main(String[] args) {
        OfficeService f = new OfficeService();
        try {
            Map<String , FileMeta> list =  f.copyFileMetas(new String[]{"003720de18c64c2c9443e1a187ba0dca"} , null);
            list.forEach((k,v) ->{
                System.out.println(k+":" + v.getResourceId());
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}
